/**
 * 认证状态管理Slice
 * 管理用户登录、登出、权限验证等认证相关状态
 * 
 * 功能说明：
 * - 用户登录状态管理
 * - 登录凭据验证
 * - 用户信息存储
 * - 权限管理
 * - 自动登录状态恢复
 * 
 * @author 项目开发团队
 * @version 1.0.0
 */

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { authService } from '../../services/authService'

// 异步thunk - 用户登录
export const login = createAsyncThunk(
  'auth/login',
  async (credentials, { rejectWithValue }) => {
    try {
      const response = await authService.login(credentials)
      return response
    } catch (error) {
      return rejectWithValue(error.message)
    }
  }
)

// 异步thunk - 发送短信验证码
export const sendSmsCode = createAsyncThunk(
  'auth/sendSmsCode',
  async (phone, { rejectWithValue }) => {
    try {
      const response = await authService.sendSmsCode(phone)
      return response
    } catch (error) {
      return rejectWithValue(error.message)
    }
  }
)

// 异步thunk - 验证登录状态
export const verifyAuth = createAsyncThunk(
  'auth/verifyAuth',
  async (_, { rejectWithValue }) => {
    try {
      const response = await authService.verifyAuth()
      return response
    } catch (error) {
      return rejectWithValue(error.message)
    }
  }
)

// 异步thunk - 用户登出
export const logout = createAsyncThunk(
  'auth/logout',
  async (_, { rejectWithValue }) => {
    try {
      const response = await authService.logout()
      return response
    } catch (error) {
      return rejectWithValue(error.message)
    }
  }
)

// 异步thunk - 刷新token
export const refreshToken = createAsyncThunk(
  'auth/refreshToken',
  async (_, { rejectWithValue }) => {
    try {
      const response = await authService.refreshToken()
      return response
    } catch (error) {
      return rejectWithValue(error.message)
    }
  }
)

// 异步thunk - 修改密码
export const changePassword = createAsyncThunk(
  'auth/changePassword',
  async (passwordData, { rejectWithValue }) => {
    try {
      const response = await authService.changePassword(passwordData)
      return response
    } catch (error) {
      return rejectWithValue(error.message)
    }
  }
)

// 初始状态
const initialState = {
  // 认证状态
  isAuthenticated: false,
  isLoading: false,
  error: null,
  
  // 用户信息
  user: null,
  token: null,
  
  // 权限信息
  permissions: [],
  
  // 登录方式
  loginMethod: null, // 'phone' | 'idcard'
  
  // 自动登录状态
  autoLogin: true,
  
  // 登录时间
  loginTime: null,
  
  // 会话过期时间
  sessionExpiry: null
}

// 创建slice
const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    // 清除错误信息
    clearAuthError: (state) => {
      state.error = null
    },
    
    // 设置自动登录状态
    setAutoLogin: (state, action) => {
      state.autoLogin = action.payload
    },
    
    // 更新用户信息
    updateUserInfo: (state, action) => {
      if (state.user) {
        state.user = { ...state.user, ...action.payload }
      }
    },
    
    // 设置权限
    setPermissions: (state, action) => {
      state.permissions = action.payload
    },
    
    // 重置认证状态
    resetAuthState: (state) => {
      return { ...initialState }
    },
    
    // 设置登录方式
    setLoginMethod: (state, action) => {
      state.loginMethod = action.payload
    },
    
    // 更新会话过期时间
    updateSessionExpiry: (state, action) => {
      state.sessionExpiry = action.payload
    }
  },
  extraReducers: (builder) => {
    builder
      // 登录
      .addCase(login.pending, (state) => {
        state.isLoading = true
        state.error = null
      })
      .addCase(login.fulfilled, (state, action) => {
        state.isLoading = false
        state.isAuthenticated = true
        state.user = action.payload.user
        state.token = action.payload.token
        state.loginTime = new Date().toISOString()
        state.sessionExpiry = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString() // 24小时后过期
        state.error = null
      })
      .addCase(login.rejected, (state, action) => {
        state.isLoading = false
        state.isAuthenticated = false
        state.user = null
        state.token = null
        state.error = action.payload
      })
      
      // 发送短信验证码
      .addCase(sendSmsCode.pending, (state) => {
        state.isLoading = true
        state.error = null
      })
      .addCase(sendSmsCode.fulfilled, (state) => {
        state.isLoading = false
        state.error = null
      })
      .addCase(sendSmsCode.rejected, (state, action) => {
        state.isLoading = false
        state.error = action.payload
      })
      
      // 验证登录状态
      .addCase(verifyAuth.pending, (state) => {
        state.isLoading = true
        state.error = null
      })
      .addCase(verifyAuth.fulfilled, (state, action) => {
        state.isLoading = false
        state.isAuthenticated = true
        state.user = action.payload.user
        state.error = null
      })
      .addCase(verifyAuth.rejected, (state, action) => {
        state.isLoading = false
        state.isAuthenticated = false
        state.user = null
        state.token = null
        state.error = action.payload
      })
      
      // 登出
      .addCase(logout.pending, (state) => {
        state.isLoading = true
        state.error = null
      })
      .addCase(logout.fulfilled, (state) => {
        state.isLoading = false
        state.isAuthenticated = false
        state.user = null
        state.token = null
        state.permissions = []
        state.loginTime = null
        state.sessionExpiry = null
        state.error = null
      })
      .addCase(logout.rejected, (state, action) => {
        state.isLoading = false
        state.error = action.payload
        // 即使登出失败，也清除本地状态
        state.isAuthenticated = false
        state.user = null
        state.token = null
        state.permissions = []
        state.loginTime = null
        state.sessionExpiry = null
      })
      
      // 刷新token
      .addCase(refreshToken.fulfilled, (state, action) => {
        state.token = action.payload.token
        state.sessionExpiry = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
      })
      
      // 修改密码
      .addCase(changePassword.pending, (state) => {
        state.isLoading = true
        state.error = null
      })
      .addCase(changePassword.fulfilled, (state) => {
        state.isLoading = false
        state.error = null
      })
      .addCase(changePassword.rejected, (state, action) => {
        state.isLoading = false
        state.error = action.payload
      })
  }
})

// 导出actions
export const {
  clearAuthError,
  setAutoLogin,
  updateUserInfo,
  setPermissions,
  resetAuthState,
  setLoginMethod,
  updateSessionExpiry
} = authSlice.actions

// 导出selectors
export const selectIsAuthenticated = (state) => state.auth.isAuthenticated
export const selectUser = (state) => state.auth.user
export const selectToken = (state) => state.auth.token
export const selectAuthLoading = (state) => state.auth.isLoading
export const selectAuthError = (state) => state.auth.error
export const selectPermissions = (state) => state.auth.permissions
export const selectLoginMethod = (state) => state.auth.loginMethod
export const selectAutoLogin = (state) => state.auth.autoLogin
export const selectLoginTime = (state) => state.auth.loginTime
export const selectSessionExpiry = (state) => state.auth.sessionExpiry

// 检查会话是否过期
export const selectIsSessionExpired = (state) => {
  const sessionExpiry = state.auth.sessionExpiry
  if (!sessionExpiry) return false
  return new Date() > new Date(sessionExpiry)
}

// 检查用户权限
export const selectHasPermission = (permission) => (state) => {
  const permissions = state.auth.permissions
  return permissions.includes(permission) || permissions.includes('admin')
}

// 导出reducer
export default authSlice.reducer
